<?php

class FormAction_Options extends FormAction
{

  protected $action = Form::ACTION_OPTIONS;

  public function __construct(Form $form)
  {
    parent::__construct($form);
  }

  public function execute()
  {
    $this->loadData();

    if ($this->hasPostData()) {
      $this->setDataFromPost();

      $this->save();

      return true;
    }

    return false;
  }

  public function render()
  {
    return parent::render();
  }

  protected function save()
  {
    foreach ($this->data as &$row) {
      foreach ($row as $name => $value) {
        Options::update($name, $value);
      }
    }
  }

  public function loadData()
  {
    $elements = $this->form->getElements($this->action);

    $data = array();

    while ($element = $elements->next()) {
      $name = $element->getName();
      $data[$name] = Options::value($name);
    }

    $this->data[] = $data;
  }

  public function getTemplate()
  {
    return dirname(__file__) . '/../view/form_form_view.php';
  }

}
